# -*- coding:utf-8 -*-
import threading
import InitConfig as config
import urllib2
import logging
import logSendConfig
import os,commands
import rpcServer
import import_thread

a = config.Config()
ip = a.getCobblerIp()
port = a.getCobblerPort()
log_path = a.getLogPath()
os_path = a.getOsPath()
logging.basicConfig(filename = log_path, level = logging.DEBUG)
importTHread = import_thread.listionExport()

# OS = ['rhel-6.5-x86_64.iso', 'CentOS-4.5-x86_64.iso']

class MyThread(threading.Thread):
  def __init__(self, func, args, name=''):
    threading.Thread.__init__(self)
    self.name = name
    self.func = func
    self.args = args

  def getResult(self):
    return self.res

  def run(self):
    self.res = apply(self.func, self.args)

def downloadFile(taskId,osName, tofile,arch):
    '''
    download os and exec os import
    :param taskId: taskId
    :param osName: os name
    :param tofile: targdir
    :param arch: os arch
    :return:
    '''
    url =os_path+osName
    downloadType  = True;
    errorMsg = ''
    try:
        f = urllib2.urlopen(url)
        outf = open(tofile, 'wb')
        c = 0
        while True:
            s = f.read(1024 * 32)
            if len(s) == 0:
                break
            outf.write(s)
            c += len(s)
            # print('%s Download %d' % (tofile,c))
        # log_file.writeTextLog("download", content="download %s success" % (url))
        # return True
    except Exception as ex:
        downloadType = False
        logging.debug(ex)
        errorMsg = ex

    if not downloadType:
        # download error
        logSendConfig.downloadStatus(taskId,osName,3,errorMsg)
        return False
    else:
        logSendConfig.downloadStatus(taskId,osName,2,'')
        importName = osName[:osName.rfind(".")]
        mountUrl = "/var/www/html/os/%s" % (importName)
        try:
            if not os.path.exists(mountUrl):
                os.mkdir(mountUrl)
            a,b = commands.getstatusoutput('mount -t iso9660 -o loop /usr/local/src/%s %s'%(osName,mountUrl))
            if a == 0 or a =="0" :
                #success,next step  import
                server ,token =rpcServer.getCobblerService()
                importId = server.background_import({"name":"%s"%(importName),"arch":"%s"%(arch),"path":"%s"%(mountUrl)},token)
                importTHread.addLink(["%s"%(importId),"%s"%(osName),"%s"%(taskId)])
            else:
                logSendConfig.importStatus(taskId,osName,3,'mount -t iso9660 -o loop /usr/local/src/%s %s error'%(osName,mountUrl))
        except Exception as ex:
            logging.error(ex)
            logSendConfig.importStatus(taskId,os,3,ex)

def pushOsFile(taskId,OSName,tarPath,arch):
    '''
    push download and import to thread
    :param taskId:
    :param OSName:
    :param tarPath:
    :param arch:
    :return:
    '''
    t = MyThread(downloadFile,(taskId,OSName,tarPath,arch),'tread-for-%s'%(taskId))
    t.start()


#
# def main():
#   threads = []
#   nloops = range(len(OS))
#
#   for i in nloops:
#     t = MyThread(downloadFile, (OS[i],OS[i],"/usr/local/src/%s"%(OS[i],arch)),'thraed-for:%s'%(OS[i]))
#     threads.append(t)
#
#   for i in nloops:
#     threads[i].start()
#
#
# if __name__ == '__main__':
#   main()
